import type React from 'react';
import { DatePicker } from 'antd';
import type { DatePickerProps } from 'antd';
import useFormInstance from 'antd/es/form/hooks/useFormInstance';

interface FormattedDatePickerProps extends DatePickerProps {
  name: string;
}

const FormattedDatePicker: React.FC<FormattedDatePickerProps> = ({
  name,
  onChange,
  ...rest
}) => {
  const form = useFormInstance();

  const handleChange: DatePickerProps['onChange'] = (date, dateString) => {
    if (date) {
      form.setFieldValue(name, date.format('YYYY-MM-DD'));
    } else {
      form.setFieldValue(name, null);
    }
    onChange?.(date, dateString);
  };

  return (
    <DatePicker
      {...rest}
      format="YYYY-MM-DD"
      onChange={handleChange}
      style={{ width: '100%', ...(rest.style || {}) }}
    />
  );
};

export default FormattedDatePicker;
